package com.qf.web.servlet.admin;

import com.qf.domain.Goods;
import com.qf.domain.User;
import com.qf.service.GoodsService;
import com.qf.service.UserService;
import com.qf.service.impl.GoodsServiceImpl;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.StringUtils;
import com.qf.web.servlet.BaseServlet;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.UUID;

@MultipartConfig()
@WebServlet(value = "/admin/adminServlet")

public class adminServlet extends BaseServlet {
    //后台登陆页面
    public String adminLogin(HttpServletRequest request, HttpServletResponse response){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (StringUtils.empty(username)){
            request.setAttribute("msg","账户不能为空");
            return "/admin/login.jsp";
        }
        if (StringUtils.empty(password)){
            request.setAttribute("msg","密码不能为空");
            return "/admin/login.jsp";
        }
        UserService userService=new UserServiceImpl();
        User login = userService.login(username, password);
        if (login==null){
            request.setAttribute("msg","账号不存在");
            return "/admin/login.jsp";
        }
        if (login.getRole()!=0){
            request.setAttribute("msg","您的账户没有管理员权限");
            return "/admin/login.jsp";
        }
        request.setAttribute("admin",login);
        request.getSession().setAttribute("admin1",login);
        return "/admin/admin.jsp";
    }
    //添加商品
    public String addGoods(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        response.setContentType("text/html;charset=utf-8");
//        User admin1 = (User) request.getSession().getAttribute("admin1");
//        if (admin1 == null) {
//            response.getWriter().write("<script>alert('-1');window.location='addGoods.jsp'</script>");
//            return null;
//        }
//        String[] strings=new String[6];
//        int i=0;
//        String imgss = null;
//        Collection<Part> parts = request.getParts();
//        if (parts != null) {
//            for (Part part : parts) {
//                String submittedFileName = part.getSubmittedFileName();
//                if (submittedFileName == null) {
//                    strings[i]=request.getParameter(part.getName());
//                    i++;
//                    continue;
//                } else {
//                    if (submittedFileName.equals("")) {
//                        response.getWriter().write("<script>alert('加载信息失败3');window.location='addGoods.jsp'</script>");
//                        return null;
//                    }
//                    //创建文件夹
//                    String realPath = this.getServletContext().getRealPath("/WEB-INF/IMGSS");
//                    File file = new File(realPath);
//                    if (!file.exists()) {
//                        file.mkdirs();
//                    }
//
//                    if (part.getName().equals("picture")) {
//                        String uuid = UUID.randomUUID().toString().replace("-", "");
//                        //不加1可能报错  无法退出循环
//                        String s = submittedFileName.substring(submittedFileName.lastIndexOf(".") + 1);
//                        imgss = uuid + "." + s;
//                        part.write(imgss);
//
//                    }
//
//                }
//            }
//
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//            Goods goods = new Goods(0, strings[0], simpleDateFormat.parse(strings[2]), imgss, new BigDecimal(strings[3]), Integer.parseInt(strings[4]), strings[5], Integer.parseInt(strings[1]));
//            System.out.println(goods.toString());
//            try {
//
//                System.out.println(goods.toString());
//                GoodsService goodsService = new GoodsServiceImpl();
//                goodsService.addGoods(goods);
//                return "redirect:/admin/adminServlet?method=getGoods";
//            } catch (Exception e) {
//                e.printStackTrace();
//                response.getWriter().write("<script>alert('加载信息失败2');window.location='addGoods.jsp'</script>");
//                return null;
//            }
//
//        }else {
//            response.getWriter().write("<script>alert('加载信息失败1');window.location='addGoods.jsp'</script>");
//            return null;
//        }
//
//
//    }
//    public String getGoods(HttpServletRequest request, HttpServletResponse response){
//        return "/admin/admin.jsp";
//    }
        request.setCharacterEncoding("utf-8");
        String name = request.getParameter("name");
        String typeid = request.getParameter("typeid");
        String pubdate = request.getParameter("pubdate");
        String price = request.getParameter("price");
        String star = request.getParameter("star");
        Part picture = request.getPart("picture");
        String intro = request.getParameter("intro");

       response.setContentType("text/html;charset=utf-8");
        //3数据校验
        if(StringUtils.empty(name)){
            response.getWriter().write("<script>alert('商品名称不能为空1');window.location='addGoods.jsp'</script>");
            return null;
        }
        if(StringUtils.empty(typeid)){
            response.getWriter().write("<script>alert('商品类别不能为空');window.location='addGoods.jsp'</script>");
            return null;
        }
        if(StringUtils.empty(pubdate)){
            response.getWriter().write("<script>alert('上架时间不能为空');window.location='addGoods.jsp'</script>");
            return null;
        }
        if(StringUtils.empty(price)){
            response.getWriter().write("<script>alert('价格不能为空');window.location='addGoods.jsp'</script>");
            return null;
        }
        if(StringUtils.empty(star)){
            response.getWriter().write("<script>alert('热销指数不能为空');window.location='addGoods.jsp'</script>");
            return null;
        }
        if(StringUtils.empty(intro)){
            response.getWriter().write("<script>alert('商品介绍不能为空');window.location='addGoods.jsp'</script>");
            return null;
        }

        //4保存图片
        Collection<Part> parts = request.getParts();

        String submittedFileName = picture.getSubmittedFileName();
        //submittedFileName==null; //普通字段
        String filename=null;
        if(!submittedFileName.equals("")){//是文件，但是没有上传文件
            //上传了文件
            //保存图片
            //1创建文件夹
            String path = this.getServletContext().getRealPath("/goodsImgs/");
            File dir=new File(path);
            if(!dir.exists()){
                dir.mkdirs();
            }
            //2生成新的文件名
            String uuid = UUID.randomUUID().toString().replace("-", "");
            //3获取后缀
            String ext = submittedFileName.substring(submittedFileName.lastIndexOf(".")+1);
            filename=uuid+"."+ext;
            //4保存
            picture.write(path+filename);
        }

        //5 保存数据到数据库
        try {
            GoodsService goodsService=new GoodsServiceImpl();
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            Goods goods=new Goods(0, name, sdf.parse(pubdate), filename, new BigDecimal(price), Integer.parseInt(star), intro,Integer.parseInt(typeid));

            goodsService.addGoods(goods);
            return "redirect:/admin/goodsservlet?method=getGoods";
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("<script>alert('添加商品失败');window.location='addGoods.jsp'</script>");
        }
        return null;
    }
}

